package com.wsc.wisdomchina.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;
import android.widget.ProgressBar;

import com.wsc.wisdomchina.R;
import com.wsc.wisdomchina.Tools.ACache;
import com.wsc.wisdomchina.Tools.JsonTools;
import com.wsc.wisdomchina.activitity.wisdomParty.PartyUserActivity;
import com.wsc.wisdomchina.adapter.PartyContactAdapter;
import com.wsc.wisdomchina.application.MyApplication;
import com.wsc.wisdomchina.callback.ContributorView;
import com.wsc.wisdomchina.callback.ShowChatViewInterface;
import com.wsc.wisdomchina.javaBean.RespObj;
import com.wsc.wisdomchina.javaBean.wisdomParty.PartyContactListBean;
import com.wsc.wisdomchina.presenter.ContributorPresenter;

import java.util.List;

/**
 * 通讯录Fragment
 */
public class PartyContactFragment extends Fragment implements ContributorView {
    private final String PartyFragmentString = PartyContactFragment.class.getSimpleName();

    private String cid;
    private String pId;
    private String name;
    private Context mcontext;
    private int skip = 0;
    private final int limit = 50;
    private ContributorPresenter contributorPresenter;
    private List<PartyContactListBean> homeNewsList;
    private PartyContactAdapter quanBuAdapter;
    private ProgressBar pb_todayInfo;
    private MyApplication myApplication;
    private ACache aCache;
    private String aCacheFlagKey;
    private ExpandableListView contacelist;
    private boolean isClick;
    private ShowChatViewInterface mCallBack;// 接口变量

    public static PartyContactFragment newInstance(Bundle b) {
        PartyContactFragment selectedOneFragment = new PartyContactFragment();
        selectedOneFragment.setArguments(b);
        return selectedOneFragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        cid = getArguments().getString("cid");
        pId=getArguments().getString("pId");
        aCacheFlagKey=PartyFragmentString;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        View view = inflater.inflate(R.layout.partycontacefragment_layout, container, false);
        mcontext = getActivity();
        aCache=ACache.get(mcontext);
        myApplication=(MyApplication) getActivity().getApplication();
        contributorPresenter = new ContributorPresenter(this, mcontext);
        initView(view);
        return view;
    }

    /**
     * @param view
     * @Description 初始化View控件
     * @author jaily.zhang
     */
    private void initView(View view) {

        pb_todayInfo = (ProgressBar) view.findViewById(R.id.pb_studyInfo);
        contacelist=(ExpandableListView) view.findViewById(R.id.contacelist);
        contacelist.setGroupIndicator(null);
        // 监听组点击
        contacelist.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener()
        {
            @SuppressLint("NewApi")
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id)
            {

                if (homeNewsList.get(groupPosition).getPm().isEmpty())
                {
                    return true;
                }
                return false;
            }


        });

        contacelist.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
            @Override
            public void onGroupExpand(int groupPosition) {
                for (int i = 0; i < quanBuAdapter.getGroupCount(); i++) {
                    if (groupPosition != i) {
                        contacelist.collapseGroup(i);
                    }
                }
            }

        });

        // 监听每个分组里子控件的点击事件
        contacelist.setOnChildClickListener(new ExpandableListView.OnChildClickListener()
        {

            @Override
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id)
            {
                isClick=true;
                Intent intent=new Intent(mcontext, PartyUserActivity.class);
                intent.putExtra("id",homeNewsList.get(groupPosition).getPm().get(childPosition).getId());
                intent.putExtra("title",homeNewsList.get(groupPosition).getPm().get(childPosition).getName());
                startActivity(intent);
                return false;
            }
        });


    }

    /**
     * @Description 服务器获取数据
     * @author jaily.zhang
     */
    private void showData() {
        if(aCache.getAsString(aCacheFlagKey)!=null)
        {
            pb_todayInfo.setVisibility(View.GONE);
            List<PartyContactListBean> homeNewsItem = JsonTools.jsonStringToList(aCache.getAsString(aCacheFlagKey), PartyContactListBean.class);
            if (homeNewsItem != null && homeNewsItem.size() > 0) {
                homeNewsList = homeNewsItem;
                quanBuAdapter = new PartyContactAdapter(mcontext, homeNewsList);
                contacelist.setAdapter(quanBuAdapter);
            }
        }else
        {
            //党员通讯录
            contributorPresenter.getAddressListGetByTypeIdMemList(cid, skip, limit, PartyFragmentString);
        }

    }


    @Override
    public void onLoadContributorStart(String flag) {
        pb_todayInfo.setVisibility(View.VISIBLE);
    }


    @Override
    public void onLoadContributorSuccess(String jsonString, String flag) {
        try {
            if (flag.equals(PartyFragmentString)) {
                RespObj respObj = JsonTools.jsonStringToObject(jsonString, RespObj.class);
                String code = respObj.getCode();
                Object object = respObj.getMessage();
                if (code.equals("200") && object != null) {
                    String jsonMessage = JsonTools.objectToJsonString(object);
                    List<PartyContactListBean> homeNewsItem = JsonTools.jsonStringToList(jsonMessage, PartyContactListBean.class);
                    if (homeNewsItem != null && homeNewsItem.size() > 0) {
                        aCache.put(aCacheFlagKey,jsonMessage,2*60);
                        homeNewsList = homeNewsItem;
                        quanBuAdapter = new PartyContactAdapter(mcontext, homeNewsList);
                        contacelist.setAdapter(quanBuAdapter);
                    }else
                    {
                        aCache.clear();
                    }

                }
            }
        }catch (Exception e)
        {

        }
    }


    @Override
    public void onLoadContributorComplete(String flag) {
        pb_todayInfo.setVisibility(View.GONE);
    }

    @Override
    public void onLoadContributorError(String error, String flag) {
    }

    @Override
    public void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
    }


    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        if(isClick)
        {
            isClick=false;
        }else {
            if (myApplication.getInformationFragmentSelected() != null) {
                if (myApplication.getInformationFragmentSelected().equals(PartyFragmentString)) {
                    mCallBack.isShowChatView(false);
                    skip = 0;
                    showData();
                }
            }
        }
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mCallBack = (ShowChatViewInterface) context;
    }

}
